﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Web.Mail;
using MailMessage = System.Net.Mail.MailMessage;

namespace SportStore.DomainModel.Services
{
    public class EmailOrderSubmitter : IOrderSubmitter
    {
        private const string MailSubject = "New order submitted!";
        private string smtpServer, mailFrom, mailTo;

        public EmailOrderSubmitter(string smtpServer, string mailFrom, string mailTo)
        {
            // Received parameter from IoC container
            this.smtpServer = smtpServer;
            this.mailFrom = mailFrom;
            this.mailTo = mailTo;
        }

        public void SubmitOrder(Entities.Cart cart)
        {
            // Prepare the messsage  body
            StringBuilder body = new StringBuilder();
            body.AppendLine("A new order has been submitted");
            body.AppendLine(("---"));
            body.AppendLine("Item:");
            foreach (var line in cart.Lines)
            {
                var subTotal = line.Product.Price*line.Quantity;
                body.AppendFormat("{0} x {1} (subtotal: {2:c}", line.Quantity, line.Product.Name, subTotal);
            }

            body.AppendFormat("Total order value: {0:c}", cart.ComputeTotalValue());
            body.AppendLine("---");
            body.AppendLine("Ship to:");
            body.AppendLine(cart.ShippingDetails.Name);
            body.AppendLine(cart.ShippingDetails.Line1);
            body.AppendLine(cart.ShippingDetails.Line2 ?? string.Empty);
            body.AppendLine(cart.ShippingDetails.Line3 ?? string.Empty);
            body.AppendLine(cart.ShippingDetails.City);
            body.AppendLine(cart.ShippingDetails.State ?? string.Empty);
            body.AppendLine(cart.ShippingDetails.Country);
            body.AppendLine(cart.ShippingDetails.Zip);
            body.AppendLine("---");
            body.AppendFormat("Gift wrap: {0}", cart.ShippingDetails.GiftWrap ? "Yes" : "No");

            // Dispatch the email
            try
            {
                SmtpClient smtpClient = new SmtpClient(smtpServer);
                smtpClient.Send(new MailMessage(mailFrom, mailTo, MailSubject, body.ToString()));
            }
            catch (Exception) { }
        }
    }
}
